﻿using Kinlo.Entitys;
using Kinlo.MESDocking;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using UIWindows.GlobalStatics;
using UIWindows.Models.Devices;
using UIWindows.Models.MES;
using UIWindows.Tools.Helper;
using XingLucifer.Devices;
using XingLucifer.IBase.Enums;

namespace UIWindows.Services.PLC_MESHelper
{
    /// <summary>
    ///拆盘机左扫码
    /// </summary>
    public class DismantlingDiscLeftScanBarcode : HelperBase
    {
        PLCBase InjMachine { get; set; }

        List<ParentVO> trayScanData = new List<ParentVO>();
        MESTrayScanRecord _mesTrayScanRecord { get; set; }
        public DismantlingDiscLeftScanBarcode(
            DeviceInteractiveaddressStatic deviceInteractiveaddressStatic,
            DeviceClientModel deviceModel,
            TemporaryStatic temporaryStatic,
            ParameterStatic parameterStatic,
            DeviceConfigStatic deviceConfigStatic,
            SystemConfigStatic systemConfigStatic,
             HomeStatic homeStatic,
             Action<string, string, string, string, string, long, DateTime, string, string, string, string> log, Action<string, string, string> dialog
            ) : base(deviceInteractiveaddressStatic, deviceModel, temporaryStatic, parameterStatic, deviceConfigStatic, systemConfigStatic, homeStatic, log, dialog)
        {
            InjMachine = deviceModel.PLC;
            _mesTrayScanRecord = new MESTrayScanRecord(_log, _dialog);
            trayScanData = new List<ParentVO>(); 
        }
        int trayScanNum = 0;
        public override Task Handle()
        {
            if (_parameter == null) return base.Handle();
            //await Task.Yield();
            short testResult = 2;
            RunLog($"- { machineInfo_Type.ToString()}左扫码开始");

            try
            {
                DeviceClientModel? device = _deviceConfig.DeviceList.FirstOrDefault(x => x.ServiceName == _deviceModel.ServiceName
               && x.TaskType == TaskTypes.拆盘左扫码);
                if (device == null)
                {
                    RunLog($"- { machineInfo_Type.ToString()}左扫码 触发设备位置找不到，请注意!!!", MessageLevelType.错误);
                    return base.Handle();
                }
                var barcode = ScanCode(_parameterStatic.RunParameter.Retries_Count_ScanCode, device.Communication, 1);
                if (string.IsNullOrWhiteSpace(barcode) || barcode.Contains("ERROR"))
                {
                    testResult = 2;
                    RunLog($"【左扫码】扫码失败");
                }
                else
                {
                    testResult = 1;
                    try
                    {
                        var entityType = GetEntityType();
                        var entity = CreateEntityType<object>();

                        // 设置数据库表名
                        PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
                        tableNameProperty.SetValue(entity, Convert.ChangeType($"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}", tableNameProperty.PropertyType), null);
                        var dateNow = DateTime.Now;
                        var entityData = entity as DismantlingDiscLeftData;
                        entityData.LoadInboundTime = dateNow;
                        entityData.AcquisitionTime = dateNow;
                        entityData.NumPerPallet = "132";
                        entityData.PalletNo = barcode;
                        entityData.Position = (int)ScanPositionType.左扫码;
                        entityData.Insert();

                        trayScanNum++;  //拆盘次数+1
                        trayScanData.Add(new ParentVO()
                        {
                            RID = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}_T_{barcode}",
                            TrayNomber = barcode,
                            ScanTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        });
                    
                        _homeStatic.AddBattery(entityData, machineInfo_Type);
                    }
                    catch (Exception ex)
                    {
                        RunLog($"插入数据库【左扫码】发生异常:{ex}");
                    }

                    if (_parameterStatic.DecideParameter.EnableMES&& trayScanData.Count >= 5)
                    {
                        List<ParentVO> subset = trayScanData.Take(5).ToList();
                        //上传MES
                        MESTrayScanRecord(_mesTrayScanRecord,subset);
                        //清空五盘数据
                        trayScanData.Clear();
                    }


                    RunLog($"【左扫码】扫码成功：{barcode}");
                }
            }
            catch (Exception ex)
            {
                RunLog($"【左扫码】发生异常:{ex}");
            }
            finally
            {
                var r1 = InjMachine.Write("DM1101", new short[] { testResult });
                var r2 = InjMachine.Write("DM1100", new short[] { 1 });
                var r3 = InjMachine.Write("DM1000", new short[] { 0 });
                RunLog($"【左扫码】写结果信号 {testResult} {r1}.{r2}.{r3} {(r1 && r2 && r3 ? "成功" : "失败")}");
            }

            return base.Handle();

            //return Task.CompletedTask;
        }
    }
}
